package com.godyao.aop;

import com.godyao.enums.ResponseCodeEnum;
import com.godyao.enums.ResultMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author godyao
 * @date 2022/3/19
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(BindException.class)
    public ResultMsg handleBindException(BindException exception) {
        List<FieldError> allErrors = exception.getFieldErrors();
        StringBuilder sb = new StringBuilder();
        for (FieldError errorMessage : allErrors) {
            sb.append(errorMessage.getField()).append(": ").append(errorMessage.getDefaultMessage()).append(", ");
        }
        return new ResultMsg(1, sb.toString(), null);
    }

    @ExceptionHandler({AuthenticationException.class})
    public ResultMsg handleShiroAuthExceptionResult(Exception ex) {
        return new ResultMsg(ResponseCodeEnum.NO_AHTU.getCode(), ResponseCodeEnum.NO_AHTU.getDesc(), null);
    }


    @ExceptionHandler(Exception.class)
    public ResultMsg handleExceptionResult(Exception ex) {
        //捕获对应异常然后做操作
        //ex.printStackTrace();
        log.error(ex.getLocalizedMessage());
        return new ResultMsg(ResponseCodeEnum.FAIL.getCode(), ResponseCodeEnum.FAIL.getDesc(), null);
    }

}

